#include "thread_trace.h"

#include <stdio.h>
#include <stdlib.h>

extern int total[64];
extern char traces_id[65][MAXB];
extern unsigned long traces_time[65][MAXB / 4];
extern int total_m;
/*
int msprintf(char *buff, unsigned long time)
{
    char d;
    int r = 10;
    int i = 0;
    char s[20];
    int j = 0;
    do {
        d = (char)(time % r);
        time /= r;
        s[i++] = d + '0';
    } while (time && i < sizeof(s));
    do {
        buff[j++] = s[--i];

    } while (i);
    buff[j++] = ',';
    buff[j++] = 0;
    return j - 1;
}
*/
void trace_print(unsigned long time, char myid, const char event_name[])
{
    if (4 * total_m + 4 <= MAXB) {
        // char trace[16];
        int i = 4 * total_m;
#ifdef TARG_SW5
        traces_time[0][total_m++] = time;
#else
        traces_time[0][total_m++] = time/210*225;
#endif
        traces_id[0][i] = '0';
        traces_id[0][i + 1] = '0';
        traces_id[0][i + 2] = event_name[0];
        traces_id[0][i + 3] = event_name[1];
        /*
        int len = msprintf(trace, time);

        // strcat(traces[0],trace);
        for (i = 0; i < len; i++) {
            traces[0][total_m + i] = trace[i];
        }
        total_m += len;
        traces[0][total_m++] = '0';
        traces[0][total_m++] = ',';
        if (event_name[0] == '0') {
            traces[0][total_m++] = event_name[1];
            traces[0][total_m++] = ',';
        } else {
            traces[0][total_m++] = event_name[0];
            traces[0][total_m++] = event_name[1];
            traces[0][total_m++] = ',';
        }
    }
    */
    }
}

void print_to_file(FILE *f, int num_threads)
{
    printf("...begin_print_to_file...\n");
    f = fopen("./trace.txt", "w");
    int i, j, k;
    for (i = 0; i < total_m; i++) {
        j = 4 * i;
        fprintf(f, "%ld,", traces_time[0][i]);
        fprintf(f, "%c", traces_id[0][j]);
        fprintf(f, "%c,", traces_id[0][j + 1]);
        fprintf(f, "%c", traces_id[0][j + 2]);
        fprintf(f, "%c,", traces_id[0][j + 3]);
    }
    fprintf(f, "\n");
    for (i = 0; i < num_threads; i++) {
        for (j = 0; j < total[i]; j++) {
            k = 4 * j;
            fprintf(f, "%ld,", traces_time[i + 1][j]);
            fprintf(f, "%c", traces_id[i + 1][k]);
            fprintf(f, "%c,", traces_id[i + 1][k + 1]);
            fprintf(f, "%c", traces_id[i + 1][k + 2]);
            fprintf(f, "%c,", traces_id[i + 1][k + 3]);
        }
        fprintf(f, "\n");
    }
    fclose(f);
    printf("...end_print_to_file...\n");
}
